package chat.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import chat.entity.Account;
import chat.entity.Message;
import com.google.gson.*;
/**
 * Servlet implementation class ChatHandlerServlet
 */
@WebServlet("/ChatHandlerServlet")
public class ChatHandlerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private List<Account> accounts;
	private List<Message> messages;
	private Account account;
	private Message message;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ChatHandlerServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		// TODO Auto-generated method stub
		accounts = new ArrayList<Account>();
		messages = new ArrayList<Message>();

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String action = request.getParameter("action").toString();
		HttpSession session = request.getSession(true);
		switch (action) {
		case "login":
			String username =  request.getParameter("user").toString();
			String password = request.getParameter("pass").toString();
			account = new Account(username, password);
			accounts.add(account);
			
			
			session.setAttribute("account", account);
			
			response.sendRedirect("/ChatServlet/chat.jsp");
			break;
		case "sendMessage":
			String type = request.getParameter("type").toString();
			String content = request.getParameter("message").toString();
			Account sender = (Account) session.getAttribute("account");
			List<Account> receiver = new ArrayList<Account>();
			if(type.equals("broadcast")){
				receiver = accounts;
				message = new Message(content, sender, receiver,false);
			}else{
				
			}
			break;
		case "getMessage":
			Gson gson = new Gson();
			
			break;
		default:
			break;
		}
	}

	private Account getAccount(String username, String password) {
		for(Account acc: accounts){
			if(acc.getUsername().equals(username) && acc.getPassword().equals(password))
				return acc;
		}
		return null;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
